/*******************************************************************************
Figure12.do

This file uses data created in "Code\Data_setup\NETS_Sorting_Data.do" and plots 
a kernel regression of the relationship between log average firm employment 
density and log total firm employment, after controlling for industry fixed 
effects, for M=12. It regresses firms' log average employment densities weighted 
by number of plants on industry fixed effects, fits a kernel-weighted regression 
of the residuals on log total firm employment using a zero degree polynomial and 
the bandwidth that minimizes the conditional weighted mean integrated squared 
error, then plots the regression and 95% confidence interval.

Last updated: 6/3/2021
*******************************************************************************/

version 15
cd "C:\Plants_in_Space"
set more off
set type double
set varabbrev off
graph set window fontface "Times New Roman" 

use "Data\Final\TablesI_II_V_and_Figure13\firm_average_location_density_M12_data.dta", clear

// Regress log average employment density on industry fixed effects and collect
// the residuals
reghdfe log_estab_wght_emp_density_12, a(sic8) residuals(re_estab_wght_emp_density_12)

// Local regression of residualized log average employment density on log total
// firm employment
lpoly re_estab_wght_emp_density_12 log_firm_employment, n(500) se(standarderrors) generate(log_firm_employment_smooth re_emp_density_12_grid) nograph
gen upperinterval = min(re_emp_density_12_grid + 1.96*standarderrors, 2) if !missing(standarderrors)
gen lowerinterval = re_emp_density_12_grid - 1.96*standarderrors

twoway (rarea upperinterval lowerinterval log_firm_employment_smooth, lcolor(gs12) fcolor(gs11)) ///
	   (line re_emp_density_12_grid log_firm_employment_smooth, lcolor(navy)), ///
	xtitle("Log Total Firm Employment", size(large)) ytitle("Log Average Employment Density of" "Plants' Locations (Controlling for Industry)", size(large)) ///
	xlabel(0 "10{superscript:0}" 2.3025851 "10{superscript:1}" 4.6051702 "10{superscript:2}" 6.9077553 "10{superscript:3}" 9.2103404 "10{superscript:4}" 11.512925 "10{superscript:5}" 13.815511 "10{superscript:6}", labsize(large)) ///
	yscale(range(-0.2 2)) ylabel(, labsize(large) nogrid) ///
	plotregion(fcolor(white)) graphregion(color(white)) bgcolor(white) title("") legend(off) note("")
graph export "Plots\Figure12.png", as(png) replace

// The above regression takes some time to run. Save the estimates and 
// confidence interval in case we want to remake the figure without rerunning
// the regression.
save "Data\Final\TablesI_II_V_and_Figure13\Figure13.dta", replace
